package com.xcc.wchatrobot;

import android.text.TextUtils;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class UserMsg {
    public String userId;
    public String userName;
    public int total;//发送消息计数
    //图灵发回来的信息
    private List<String> msgList = new ArrayList<>();
    private OnMsgListener onMsgListener;

    public UserMsg setOnMsgListener(OnMsgListener onMsgListener) {
        this.onMsgListener = onMsgListener;
        if (msgList.size() > 0 && onMsgListener != null) {
            onMsgListener.OnMsg(msgList);
            total -= msgList.size();
            msgList.clear();
        }
        return this;
    }

    public UserMsg(String userName) {
        this.userName = userName;
        int i = userName.hashCode();
        i = new Random().nextInt(9999) + i;
        userId = "" + i;
    }

    //收到信息
    public void receiveMsg(String msg) {
        if (TextUtils.isEmpty(msg)) return;
        total++;
        //开启线程访问数据
        SendTuLin sendTuLin = new SendTuLin(userId, msg);
        new HttpClient()
                .setHttpType(HttpClient.HttpType.JSON)
                .setSendTuLin(sendTuLin)
                .httpRequest(SendTuLin.API_URL, new BaseRequestBack<RetTuLin>() {
                    public RetTuLin jsonToMode(String jsonStr) {
                        return new Gson().fromJson(jsonStr, RetTuLin.class);
                    }

                    public void onResponseSucc(RetTuLin ret) {
                        if (ret.isOk()) {
                            String text = ret.getText();
                            msgList.add(text);
                            //处理信息
                            if (onMsgListener != null) {
                                onMsgListener.OnMsg(msgList);
                                total -= msgList.size();
                                msgList.clear();
                            }
                        } else total--;
                    }

                    public void onResponseFail(String retStr) {
                        total--;
                    }
                });
        ;
    }

    public interface OnMsgListener {
        public void OnMsg(List<String> msgList);
    }
}
